<?php

namespace App\Http\Controllers\Admin;

use App\Models\Notice;
use App\Models\SubOrder;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Models\Order;
use App\Interfaces\OrderService;
use App\Models\User;
use App\Models\Shop;
use App\Models\Goods;
use App\Models\PushTarrif;
use Excel;
use App\Models\OrderGoods;
use App\Models\OrderDistributes;
use App\Commands\OperationLogCommand;
use Gate;
use App\Exceptions\Admin\PermissionDeniedException;
use App\Exceptions\Interfaces\OrderServiceException;
use App\Interfaces\PushTarrifService;
use Auth,Log;
use App\Services\OrderDistribute;
use App\Interfaces\OrderDistributesService;

class OrderController extends Controller
{

    public function order_query(){

        if (!Gate::allows('order_query','')) {
            throw new PermissionDeniedException();
        }//end if()
    }//end func order_query()

    public function order_shipping(){

        if (!Gate::allows('order_shipping','')) {
            throw new PermissionDeniedException();
        }//end if()
    }//end func order_shipping()


    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request,User $user,Shop $shop)
    {
        $this->order_query();
        $query =  Order::orderBy('add_time','desc')->withTrashed();

        $filter = [
            'order_type' => $request->get('order_type'),
            'shop_id' => $request->get('shop_id'),
            'order_sn' => $request->get('order_sn'),
            'consignee'=>$request->get('consignee'),
            'mobile'=>$request->get('mobile'),
            'order_price'=>$request->get('order_price'),
            'order_status'=>$request->get('order_status'),
            'time'=>$request->get('time'),
            'create_order_device' => $request->get('create_order_device'),
        ];

        //订单类型
        if ($filter['order_type']&&$filter['order_type']!='ALL'){

            if ($filter['order_type']=='E') $orderType = 1;
            if ($filter['order_type']=='C') $orderType = 0;

            $query = $query->where('order_type',$orderType);
        }
        //商铺类型
        if ($filter['shop_id']&&$filter['shop_id']!='ALL'){

            $query = $query->where('shop_id',$filter['shop_id']);
        }
        //订单号搜索
        if ($filter['order_sn']!=''){
            $query = $query->where('order.order_sn',trim($filter['order_sn']));
        }
        //收货人搜索
        if ($filter['consignee']!=''){

            $query = $query->where('order.consignee','like',"%".$filter['consignee']."%");
        }
        //收货人电话搜索
        if ($filter['mobile']!=''){
            $query = $query->where('order.mobile','like',"%".trim($filter['mobile'])."%");
        }
        //订单价格搜索
        if ($filter['order_price']!=''&& $filter['order_price']!='All'){
            $order_price = explode('-',$filter['order_price']);
            if($order_price[1]){
                $query = $query->where('order.order_price','>=',$order_price[0]);
                $query = $query->where('order.order_price','<=',$order_price[1]);

            }else{
                $query = $query->where('order.order_price','>=',$order_price[0]);
            }

        }
        //订单状态
        if ($filter['order_status']&&$filter['order_status']!='ALL'){
            if($filter['order_status']=='7'){
                $query = $query->onlyTrashed();
            }else{
                $query = $query->where('order.order_status',$filter['order_status']);
            }
        }


        //时间
        if ($filter['time']&&$filter['time']!='ALL'){
            $time = explode('|',$filter['time']);

            $query = $query->where('order.add_time','>=',$time[0]);
            $query = $query->where('order.add_time','<=',$time[1]);
        }

        //订单来源
        if (isset($filter['create_order_device']) && $filter['create_order_device']!='ALL'){

            $query = $query->where('create_order_device',$filter['create_order_device']);
        }

        //订单状态：1:待支付; 2:待发货；3:已发货；4:已完成；5:已取消；
        $orderStatusArr = ['0'=>'状态', '1'=>'待支付','2'=>'待发货','3'=>'已发货','4'=>'已完成','5'=>'已取消','6'=>'已退款','7'=>'已删除'];

        $shops = Shop::all();

        $shopsArr[0] = '店铺';
        foreach ($shops as $shop){
            $shopsArr[$shop->id] = $shop->shop_name;
        }

        //如果是导出excel
        if ($request->get('export')==1){

            return $this->export($query);

        }

        $downloadUrl = $request->fullUrl();
        if (strpos($downloadUrl,'?')==true){
            $downloadUrl = $downloadUrl.'&export=1';
        }else{
            $downloadUrl = $downloadUrl.'?export=1';

        }

        $typeArr = ['0'=>'普通', '1'=>'外贸'];

        $orderInfo = $query->paginate(10);

        return view('admin.order.index', compact('orderInfo','orderStatusArr','refundStatusArr','user','shop','filter','shopsArr','downloadUrl','typeArr'));

    }//end func index()





    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id,OrderService $orderService,User $user,Shop $shop,Goods $goods_detail, Request $request)
    {
        $back_url = '';
        if($request->back_url){
            $back_url = $request->back_url;
        }
        if (!Gate::allows('order_query','') && !Gate::allows('order_shipping','')) {
            throw new PermissionDeniedException();
        }//end if()
        $order = $orderService->getByOrderId($id);

        $userInfo = '';
        if($order->user_id){
            $userInfo = User::findOrNew($order->user_id);
        }

        $shippingList = config('shipping');

        foreach($shippingList as $k=>$v){
            $shippingList[$k] = $v['name'];
        }
        //dd($shippingList);
        //dd($order);
        $pushTarrif = PushTarrif::where('order_id', $id)->first();

        $shippingTypeArr = ['0'=>'选择快递', '1'=>'申通速递', '2'=>'圆通速递'];

        return view('admin.order.detail',compact(['order','user','shippingList','shop','goods_detail', 'userInfo', 'back_url', 'pushTarrif', 'shippingTypeArr']));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($order_id, Request $request, OrderService $orderService)
    {

        if (!Gate::allows('order_query','') && !Gate::allows('order_shipping','')) {
            throw new PermissionDeniedException();
        }//end if()

        $shipping_name = $request->shipping_name;
        $shipping_id = $request->shipping_id;

        $result = $orderService->deliverGoods($order_id, $shipping_id, $shipping_name);

        if(!$result){

            $status = $orderService->getStatus();
            $error = $orderService->getError();

            return false;
        }//end if()

        //return $result;

    }//end func edit()

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }//end func update()

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }//end func destroy()



    /**
     * 订单详情
     *
     * @date 2015/12/09
     * @author Leen
     */
    public function detail($order_identification, OrderService $orderService){

        if (!Gate::allows('order_query','') && !Gate::allows('order_shipping','')) {
            throw new PermissionDeniedException();
        }//end if()

        /*$return = ['status'=>0, 'message'=>'', 'data'=>''];

        if(empty(intval($order_identification))){
            $return['status'] = 1;
            $return['message'] = '订单id或订单编号不能为空';

            return Response()->json($return);
        }//end if()*/

        if(intval($order_identification)>0){

            $orderInfo = $orderService->getByOrderId($order_identification);

        }else{

            $orderInfo = $orderService->getByOrderSn($order_identification);

        }//end if()
        $orderInfo = $orderInfo->toArray()[0];

        return view('admin.order.detail', compact('orderInfo'));

    }//end func detial()


    public function deliver($order_id,OrderService $orderService,Request $request, PushTarrifService $pushTarrifService){

        if (!Gate::allows('order_query','') && !Gate::allows('order_shipping','')) {
            throw new PermissionDeniedException();
        }//end if()

        $this->order_shipping();

        $order = $orderService->getByOrderId($order_id);

        if ($order->order_type){

            $orderService->shippingTarrif($order_id, $request->send_shipping_type,  $request->version);
            $this->dispatch(
                new OperationLogCommand('发货','Order','order_id:'.$order_id)
            );

            //增加推关订单任务
            $order_id = $order->order_id;
            $order_sn = $order->order_sn;
            $push_tarrif_status = 1;

            $pushTarrifService->createPushTarrif($order_id, $order_sn, $push_tarrif_status);

            return response()->json(['status'=>'success','message'=>'发货成功']);

        }else{
            $current_time = date('Y-m-d H:i:s');
            $orderService->shipping($order_id,$request->get('shipping_type'),$request->get('shipping_num'), $current_time);
            $this->dispatch(
                new OperationLogCommand('发货','Order','order_id:'.$order_id)
            );
            return response()->json(['status'=>'success','message'=>'发货成功']);

        }

        return response()->json(['status'=>'success','message'=>'发货成功']);

    }

    public function refund($order_id,OrderService $orderService,Request $request){
        if (!Gate::allows('order_query','') && !Gate::allows('order_refund','')) {
            throw new PermissionDeniedException();
        }//end if()
        //$order_id = $request->get('order_id');
        $refund_num = $request->get('refund_num');
        $refund_fee = $request->get('refund_fee');
        $refund_reason = $request->get('refund_reason');
        $refund_time = date('Y-m-d H:i:s');
        $orderService->refund($order_id,$refund_num,$refund_fee,$refund_reason,$refund_time);

        $this->dispatch(
            new OperationLogCommand('退款','Order','order_id:'.$order_id)
        );
        return response()->json(['status'=>'success','message'=>'退款成功']);
    }

    public function record($order_id,Request $request){
        //dd($request->all());
        $order_record = $request->record;
        if(mb_strlen($order_record)>255){
            return response()->json(['status'=>'error','message'=>'不超过255个字']);
        }
        $order = Order::find($order_id);
        $order->order_record = $order_record;
        $order->save();
        return response()->json(['status'=>'success']);
    }

    public function pushPay($order_id,OrderService $orderService){

        if (!Gate::allows('order_query','') && !Gate::allows('order_shipping','')) {
            throw new PermissionDeniedException();
        }//end if()

        $pay_type = Order::where('order_id', $order_id)->pluck('pay_type');

        switch ($pay_type) {
            case 'alipay':

                $orderService->pushAlipay($order_id);
                break;

            case 'wxpay':

                try {

                    $orderService->pushWxpay($order_id);

                } catch (OrderServiceException $e) {

                    throw new OrderServiceException($e->getMessage());
                }

                break;

            default:
                # code...
                break;
        }
        // $orderService->pushAlipay($order_id);
        return response()->json(['status'=>'success','message'=>'推送成功']);


    }

//    public function refund($order_id,OrderService $orderService){
////        if (!Gate::allows('order_query','') && !Gate::allows('order_refund','')) {
////            throw new PermissionDeniedException();
////        }//end if()
//        Log::info('order_id='.$order_id);
//
//        $order = Order::find($order_id);
//        if ($order->refund_status==2) throw new OrderServiceException('该订单已退款');
//
//        $pay_type = Order::where('order_id', $order_id)->pluck('pay_type');
//        Log::info('支付类型pay_type'.$pay_type);
//        switch ($pay_type) {
//            case 'alipay':
//                Log::info('退款申请结果alipay');
//                $alipay = app('alipay.web');
//                //$alipayrefund->setSellerEmail('1045832553@qq.com');
//                $alipay->setBatchNo(date('Ymd').'001');
//                $alipay->setBatchNum(1);
//                $alipay->setDetailData($alipay->pay_num.'^'.'0.01'.'^协商退款');
//                return redirect($alipay->refund());
//                //$orderService->refundAlipay($order_id);
//                break;
//
//            case 'wxpay':
//                Log::info('退款申请结果wxpay');
//                try {
//                    Log::info('退款申请结果wxpay');
//                    $orderService->refundWxpay($order_id);
//
//                } catch (OrderServiceException $e) {
//                    Log::info('订单['.$order_id.']微信退款申请失败,原因:'.$e->getMessage());
//                    throw new OrderServiceException($e->getMessage());
//                }
//
//                break;
//
//            default:
//                # code...
//                break;
//        }
//
//        // $orderService->pushAlipay($order_id);
//        return response()->json(['status'=>'success','message'=>'退款成功']);
//
//    }
    /*public function pushWxpay($order_id,OrderService $orderService){

        if (!Gate::allows('order_query','') && !Gate::allows('order_shipping','')) {

            throw new PermissionDeniedException();
        }

        $orderService->pushWxpay($order_id);

        return response()->json(['status'=>'success','message'=>'推送成功']);
    }*/

    public function pushTarrif($order_id,OrderService $orderService, PushTarrifService $pushTarrifService){

        $this->order_query();


        $isTarrif = PushTarrif::where('order_id', $order_id)->first();

        if($isTarrif->push_tarrif_status==1){

             $optType = 1;
        }else{
             $optType = 2;
        }

        $orderService->pushTarrif($order_id,$optType);

        $this->dispatch(
            new OperationLogCommand('推送','Order','order_id:'.$order_id)
        );

        return response()->json(['status'=>'success','message'=>'推送成功']);
    }

    public function pushTarrifOld($order_id,OrderService $orderService, PushTarrifService $pushTarrifService){

        $this->order_query();


        $isTarrif = PushTarrif::where('order_id', $order_id)->first();

        if($isTarrif->push_tarrif_status==1){

             $optType = 1;
        }else{
             $optType = 2;
        }

        $orderService->pushTarrifOld($order_id,$optType);

        $this->dispatch(
            new OperationLogCommand('推送','Order','order_id:'.$order_id)
        );

        return response()->json(['status'=>'success','message'=>'推送成功']);
    }



    //导出EXCEL
    public function export($query){

        if (!Gate::allows('order_query','') && !Gate::allows('order_shipping','')) {
            throw new PermissionDeniedException();
        }//end if()
        $year_code = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
        $fileName = $year_code[intval(date('Y')) - 2010] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('d', rand(0, 99));
        $title = array('订单编号', '运单号', '订单状态', '商品类型', '商铺名称', '订单时间', '商品条形码', '商品货号', '商品名称', '商品价格', '运费', '税费', '销售总价', '优惠券金额', '折扣金额', '买家实际支付金额', '支付类型', '商品数量', '收货人姓名', '身份证号', '联系电话', '所在省', '所在市', '所在区', '详细地址', '备注', '订单备录');

        $data = $query->get();
        Excel::create($fileName, function ($excel) use ($data, $title) {

            $excel->setTitle('订单详情');
            $excel->setCreator('阿福易购')->setCompany('阿福易购');
            $excel->sheet("订单详情", function ($sheet) use ($data, $title) {
                $sheet->freezeFirstRow();
                $sheet->setAutoSize(true);
                $sheet->row(1, $title);
                $arrayList = array();
                $orderStatusArr = ['0'=>'状态', '1'=>'待支付','2'=>'待发货','3'=>'已发货','4'=>'已完成','5'=>'已取消','6'=>'已退款','7'=>'已删除'];

                // Set width for multiple cells
                $sheet->setWidth(array(
                    'A'     =>  20,
                    'B'     =>  30,
                    'C'     =>  10,
                    'D'     =>  10,
                    'E'     =>  10,
                    'F'     =>  20,
                    'G'     =>  20,
                    'H'     =>  35,
                    'I'     =>  35,
                    'J'     =>  10,
                    'K'     =>  10,
                    'L'     =>  10,
                    'M'     =>  10,
                    'N'     =>  10,
                    'O'     =>  10,
                    'P'     =>  10,
                    'Q'     =>  20,
                    'R'     =>  12,
                    'S'     =>  12,
                    'T'     =>  20,
                    'U'     =>  15,
                    'V'     =>  20,
                    'W'     =>  20,
                    'X'     =>  20,
                    'Y'     =>  35,
                    'Z'     =>  20,
                    'AA'    =>  40
                ));

                foreach ($data as $order) {

                    $orderGoods = OrderGoods::select('order_goods.*', 'goods.goods_bar_code', 'order.order_status', 'shop.shop_name')
                        ->join('goods', 'goods.goods_id', '=', 'order_goods.goods_id')
                        ->join('order', 'order.order_id', '=', 'order_goods.order_id')
                        ->join('shop', 'shop.id', '=', 'order_goods.shop_id')
                        ->where('order.order_id', $order->order_id)
                        ->get();


                    $shop = Shop::find($order->shop_id);

                    $shop_name = '';

                    if ($shop) {

                        $shop_name = $shop->shop_name;
                    }

                    switch ($order->pay_type) {

                        case 'alipay':
                            $pay_type = '支付宝';
                            break;

                        case 'wxpay':
                            $pay_type = '微信';
                            break;

                        case 'pinganpay':
                            $pay_type = '平安银行';
                            break;

                        default:
                            $pay_type = '';
                            break;
                    }

                    foreach($orderGoods as $good){

                        $goods_price = $good->shop_price;

                        if (isset($good->goods_real_price) && $good->goods_real_price>0) {
                            $goods_price = $good->goods_real_price;
                        }

                        if($order->deleted_at){
                            $arrayList[] = array($order->order_sn ,$order->shipping_num.' ', '已删除', $good->type, $shop_name, $order->add_time, $good->goods_bar_code, $good->goods_sn, $good->goods_name, $goods_price, $order->shipping_fee, $order->order_tariff_fee, $order->order_price, $order->coupon_price, $order->discount_price, $order->pay_price, $pay_type, $good->buy_number, $order->consignee, $order->id_card.' ', $order->mobile, $order->province, $order->city, $order->district, $order->address, $order->shipping_message, $order->order_record);
                        }else{
                            $arrayList[] = array($order->order_sn ,$order->shipping_num.' ', $orderStatusArr[$order->order_status], $good->type, $shop_name, $order->add_time, $good->goods_bar_code, $good->goods_sn, $good->goods_name, $goods_price, $order->shipping_fee, $order->order_tariff_fee, $order->order_price, $order->coupon_price, $order->discount_price, $order->pay_price, $pay_type, $good->buy_number, $order->consignee, $order->id_card.' ', $order->mobile, $order->province, $order->city, $order->district, $order->address, $order->shipping_message, $order->order_record);
                        }
                    }

                }
                $sheet->rows($arrayList);
            });
        })->export('xls');  //storage_path('excel')
    }

    public function shippingOrder(Request $request,User $user,Shop $shop)
    {
        if (!Gate::allows('order_query','') && !Gate::allows('order_shipping','')) {
            throw new PermissionDeniedException();
        }//end if()

        $this->order_shipping();
        $orderStatusArr = ['0'=>'状态', '1'=>'待支付','2'=>'待发货','3'=>'已发货','4'=>'已完成','5'=>'已取消'];
        $query =  Order::orderBy('add_time','desc')->where('order.order_status',2);

        $filter = [
            'order_type' => $request->get('order_type'),
            'shop_id' => $request->get('shop_id'),
            'order_sn' => $request->get('order_sn'),
            'consignee'=>$request->get('consignee'),
            'mobile'=>$request->get('mobile'),
            'order_price'=>$request->get('order_price'),
            'time'=>$request->get('time'),
        ];

        //提醒发货的订单
        if($request->get('remind')){
            $query = $query->where('is_remind',$request->get('remind'));
        }

        //订单类型
        if ($filter['order_type']&&$filter['order_type']!='ALL'){

            if ($filter['order_type']=='E') $orderType = 1;
            if ($filter['order_type']=='C') $orderType = 0;

            $query = $query->where('order_type',$orderType);
        }
        //商铺类型
        if ($filter['shop_id']&&$filter['shop_id']!='ALL'){

            $query = $query->where('shop_id',$filter['shop_id']);
        }
        //订单号搜索
        if ($filter['order_sn']!=''){
            $query = $query->where('order.order_sn',trim($filter['order_sn']));
        }
        //收货人搜索
        if ($filter['consignee']!=''){
            $query = $query->where('order.consignee','like',"%".$filter['consignee']."%");
        }
        //收货人电话搜索
        if ($filter['mobile']!=''){
            $query = $query->where('order.mobile','like',"%".trim($filter['mobile'])."%");
        }
        //订单价格搜索
        if ($filter['order_price']&&$filter['order_price']!='All'){
            //dd()
            $order_price = explode('-',$filter['order_price']);
            if($order_price[1]){
                $query = $query->where('order.order_price','>=',$order_price[0]);
                $query = $query->where('order.order_price','<=',$order_price[1]);

            }else{
                $query = $query->where('order.order_price','>=',$order_price[0]);
            }
        }


        //时间
        if ($filter['time']&&$filter['time']!='ALL'){
            $time = explode('|',$filter['time']);

            $query = $query->where('order.add_time','>=',$time[0]);
            $query = $query->where('order.add_time','<=',$time[1]);
        }

        $shops = Shop::all();

        $shopsArr[0] = '店铺';
        foreach ($shops as $shop){
            $shopsArr[$shop->id] = $shop->shop_name;
        }

        //如果是导出excel
        if ($request->get('export')==1){

            return $this->export($query);

        }

        $downloadUrl = $request->fullUrl();
        if (strpos($downloadUrl,'?')==true){
            $downloadUrl = $downloadUrl.'&export=1';
        }else{
            $downloadUrl = $downloadUrl.'?export=1';

        }

        $typeArr = ['0'=>'普通', '1'=>'外贸'];

        $orderInfo = $query->paginate(10);

        return view('admin.order.shippingOrder', compact('orderInfo','user','shop','filter','shopsArr','downloadUrl','typeArr', 'orderStatusArr'));

    }//end func index()

    public function remind(){

        if (!Gate::allows('order_query','') && !Gate::allows('order_shipping','')) {
            throw new PermissionDeniedException();
        }//end if()

        //$remindOrderNum = Order::where('order_status',2)->where('is_remind',1)->get()->count();
        $remindNum = Notice::get()->count();
        //dd($remindOrderNum);
        return response()->json(['number'=>$remindNum]);
    }

    public function getCustomStatus($order_id,OrderService $orderService){

        if (!Gate::allows('order_query','') && !Gate::allows('order_shipping','')) {
            throw new PermissionDeniedException();
        }//end if()

        $return  = $orderService->getCustomsClearance($order_id);
        return response()->json($return);

    }


    public function orderAddress($order_id,Request $request){
        $addressField = ['province','city','district','address','consignee','mobile','id_card'];
        $data = [];
        foreach($request->all() as $k=>$v){
            if (in_array($k,$addressField)){
                $data[$k]=$v;
            }
        }
        $order = Order::find($order_id);
        $order->update($data);
        return response()->json(['status'=>'success','order'=>Order::find($order_id)]);

    }



    /**
     * [订单派发]
     * @param  [type]          $order_id        [description]
     * @param  OrderService    $orderService    [description]
     * @param  OrderDistribute $orderDistribute [description]
     * @return [type]                           [description]
     */
    public function orderDistribute($order_id, OrderService $orderService, OrderDistribute $orderDistribute){

        $return = ['isSucc'=>'false', 'msg'=>''];

        $order = $orderService->getByOrderId($order_id);

        if ($order) {

            $result = $orderDistribute->distribute($order);

            // $result = '{"isSucc":true,"msg":"订单接入成功","obj":""}';

            $resu = json_decode($result, true);

            if ($resu['isSucc']) {

                $distributes = [];

                $distributes['order_id'] = $order_id;

                $distributes['msg'] = $resu['msg'];

                if ($resu['isSucc']) {

                    $distributes['is_suc'] = 1;
                }else{

                    $distributes['is_suc'] = 0;
                }

                $orderDistributes = OrderDistributes::firstOrCreate($distributes);
            }

            return $result;
        }

        return Response()->json($return);
    }



}//end class order
